package com.xmut.xmutbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xmut.xmutbackend.entity.Users;
import com.xmut.xmutbackend.mapper.UsersMapper;
import com.xmut.xmutbackend.service.IUsersService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements IUsersService {

    @Override
    public Users login(String username, String password) {
        // 查询用户名对应的用户
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getUsername, username);

        // 使用list替代getOne，避免多个结果导致异常
        List<Users> usersList = this.list(queryWrapper);
        
        // 添加调试日志
        if (usersList.isEmpty()) {
            System.out.println("用户不存在: " + username);
            return null;
        }
        
        // 遍历所有匹配的用户，验证密码
        for (Users user : usersList) {
            System.out.println("检查用户: " + user.getUsername() + ", ID: " + user.getId());
            
            if (user.getPassword().equals(password)) {
                System.out.println("密码验证成功");
                return user;
            }
        }
        
        System.out.println("所有用户密码验证失败");
        return null;
    }
    
    @Override
    @Transactional
    public boolean register(Users user) {
        // 检查用户名是否已存在
        if (checkUsernameExists(user.getUsername())) {
            return false;
        }
        
        // 设置默认状态为1（正常）
        user.setStatus(1);
        
        // 保存用户信息
        return this.save(user);
    }
    
    @Override
    public boolean verifyUserEmail(String username, String email) {
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getUsername, username)
                   .eq(Users::getEmail, email);
        
        return this.count(queryWrapper) > 0;
    }
    
    @Override
    @Transactional
    public boolean updatePassword(String username, String newPassword) {
        LambdaUpdateWrapper<Users> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(Users::getUsername, username)
                    .set(Users::getPassword, newPassword);
        
        return this.update(updateWrapper);
    }
    
    @Override
    public boolean checkUsernameExists(String username) {
        LambdaQueryWrapper<Users> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Users::getUsername, username);
        
        return this.count(queryWrapper) > 0;
    }
}